import time
import numpy as np
import matplotlib.pyplot as plt


def exponential_moving_average(data, alpha=0.2):
    ema = [data[0]]  # 初始值
    for i in range(1, len(data)):
        ema.append(alpha * data[i] + (1 - alpha) * ema[-1])
    return np.array(ema)

def plotting(data):
    start_time = time.time()
    plt.ion()  # 开启动态画图
    time_record, gas_resistant = [], []
    fig = plt.figure(figsize=(9, 6))
    plt.xlabel(r"Time/s", fontsize=18)
    plt.ylabel(r"GR", fontsize=18)
    plt.tick_params(labelsize=12)
    # print(data[0])
    flag=False
    for index,value in enumerate(data[0]):
        plt.pause(0.1)
        time_record.append(index)
        gas_resistant.append(data[2][index])
        gas_resistant2=exponential_moving_average(gas_resistant)
        # plt.plot(time_record, gas_resistant, c="r")
        plt.plot(time_record, gas_resistant2, c="r",label="Sensor1")
        if flag is False:
            plt.legend(fontsize=14, loc="upper right")
            flag=True

    plt.ioff()
    plt.show()



def dataloader(local_txt_path):
    time_list_senor1, time_list_senor2, senor_data1, senor_data2 = [], [], [], []
    with open(local_txt_path, 'r') as file:
        text_list = file.read().split()
        for text in text_list:
            parts = text.split(":")
            time = parts[1].split("Gas")[0]  # 提取时间
            resistant = int(parts[2])  # 提取电阻值
            if abs(resistant) < 500000:
                if "Gas2_resistant" in text:
                    senor_data2.append(resistant)
                    time_list_senor2.append(time)
                else:
                    time_list_senor1.append(time)
                    senor_data1.append(resistant)

    return [time_list_senor1, time_list_senor2, senor_data1, senor_data2]


if __name__ == "__main__":
    local_txt_path = r"D:\Gas_detector\data\data3.txt"
    Data = dataloader(local_txt_path)
    plotting(Data)
